﻿using Cloud.Update.Core;
using Cloud.Update.Core.Extends;
using Cloud.Update.Core.Models;
using Cloud.Update.Core.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;

namespace Cloud.Update
{
    public class MainViewModel: INotifyPropertyChanged
    {
        private ClientParameter ClientParameter;
        Updates updates;
        public MainViewModel(ClientParameter clientParameter)
        {
            ClientParameter = clientParameter;

            updates = new Updates(ClientParameter);
            updates.AllFinish += Updates_AllFinish;
            updates.DownloadFinish += Updates_DownloadFinish;
            updates.DownProgressChanged += Updates_DownProgressChanged;
            updates.UnZipFinish += Updates_UnZipFinish;
            updates.UnZipProgressChanged += Updates_UnZipProgressChanged;

            updates.BackUpProgressChanged += Updates_BackUpProgressChanged;
            updates.BackUpFinish += Updates_BackUpFinish;
            updates.UnBackUpProgressChanged += Updates_UnBackUpProgressChanged;
            updates.UnBackUpFinish += Updates_UnBackUpFinish;
            Thread thread = new Thread(()=> {
                if (clientParameter.IsRestore)
                {
                    updates.UnBackUp();
                }
                else {
                    updates.Backup().Execute();
                }
            } );
            thread.Start();
        }
        /// <summary>
        /// 备份完成
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="state"></param>
        /// <param name="msg"></param>
        private void Updates_BackUpFinish(bool isSuccess, UpdateState state, string msg = null)
        {
            BackUpState = state.ToString();
        }

        /// <summary>
        /// 备份进度
        /// </summary>
        /// <param name="progress"></param>
        private void Updates_BackUpProgressChanged(BaseModel progress)
        {
            BackUpState = progress.State.ToString();
            ProgressBackUpValue = progress.ProgressRate;
            BackUpStep = progress.CurrentSize + "/" + progress.TotalSize;
        }

        /// <summary>
        /// 备份还原完成
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="state"></param>
        /// <param name="msg"></param>
        private void Updates_UnBackUpFinish(bool isSuccess, UpdateState state, string msg = null)
        {
            try
            {
                BackUpState = state.ToString();
                if (isSuccess)
                {                 
                    MainTitle = "还原成功,正在等待程序启动,请稍等";
                }
                else {
                    MainTitle = "还原失败了,正在尝试重新启动程序";

                }


                if (File.Exists(ClientParameter.AppName))
                {
                    Thread.Sleep(3000);
                    Process.Start(ClientParameter.AppName, "unbackup");
                }
                else
                {
                    var diaResult = MessageBox.Show("启动失败,没有找到运行主程序,点击确认关闭", "启动失败", MessageBoxButton.OK, MessageBoxImage.Error);
                    if (diaResult == MessageBoxResult.Cancel || diaResult == MessageBoxResult.OK) {
                        Process.GetCurrentProcess().Kill();
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                var diaResult = MessageBox.Show("还原成功了,但是未能正常启动,点击确认关闭\n错误信息:"+ex.ToString(), "启动失败", MessageBoxButton.OK, MessageBoxImage.Error);
                if (diaResult == MessageBoxResult.Cancel || diaResult == MessageBoxResult.OK)
                {
                    Process.GetCurrentProcess().Kill();
                }
            }
            finally
            {
                Process.GetCurrentProcess().Kill();
            }
        }

        /// <summary>
        /// 备份还原进度
        /// </summary>
        /// <param name="progress"></param>
        private void Updates_UnBackUpProgressChanged(BaseModel progress)
        {
            MainTitle = "正在将程序还原至上一版本";
            BackUpState = progress.State.ToString();
            ProgressBackUpValue = progress.ProgressRate;
            BackUpStep = progress.CurrentSize + "/" + progress.TotalSize;
        }


        #region 界面属性
        private string mainTitle = "更新程序正在运行";
        /// <summary>
        /// 标题栏
        /// </summary>
        public string MainTitle
        {
            get { return mainTitle; }
            set { mainTitle = value;RaisePropertyChanged("MainTitle"); }
        }



        private double backUpValue;
        /// <summary>
        /// 备份进度
        /// </summary>
        public double ProgressBackUpValue
        {
            get { return backUpValue; }
            set { backUpValue = value; RaisePropertyChanged("ProgressBackUpValue"); }
        }
        private string backUpStep;
        /// <summary>
        /// 备份步骤
        /// </summary>
        public string BackUpStep
        {
            get { return backUpStep; }
            set { backUpStep = value; RaisePropertyChanged("BackUpStep"); }
        }
        private string backUpState;
        /// <summary>
        /// 备份状态
        /// </summary>
        public string BackUpState
        {
            get { return backUpState; }
            set { backUpState = value; RaisePropertyChanged("BackUpState"); }
        }
        private double progressDownLoadValue;
        /// <summary>
        /// 下载进度
        /// </summary>
        public double ProgressDownLoadValue
        {
            get { return progressDownLoadValue; }
            set { progressDownLoadValue = value;RaisePropertyChanged("ProgressDownLoadValue"); }
        }
        private double progressUnZipValue;
        /// <summary>
        /// 解压进度
        /// </summary>
        public double ProgressUnZipValue
        {
            get { return progressUnZipValue; }
            set { progressUnZipValue = value; RaisePropertyChanged("ProgressUnZipValue"); }
        }

        private string downLoadState;
        /// <summary>
        /// 下载状态
        /// </summary>
        public string DownLoadState
        {
            get { return downLoadState; }
            set { downLoadState = value; RaisePropertyChanged("DownLoadState"); }
        }

        private string unZipState;
        /// <summary>
        /// 解压状态状态
        /// </summary>
        public string UnZipState
        {
            get { return unZipState; }
            set { unZipState = value; RaisePropertyChanged("UnZipState"); }
        }
        private string downLoadStep;
        /// <summary>
        /// 下载步骤
        /// </summary>
        public string DownLoadStep
        {
            get { return downLoadStep; }
            set { downLoadStep = value; RaisePropertyChanged("DownLoadStep"); }
        }

        private string unZipStep;
        /// <summary>
        /// 解压步骤
        /// </summary>
        public string UnZipStep
        {
            get { return unZipStep; }
            set { unZipStep = value; RaisePropertyChanged("UnZipStep"); }
        }
        #endregion


        /// <summary>
        /// 下载进度
        /// </summary>
        /// <param name="progress"></param>
        private void Updates_DownProgressChanged(DownLoadModel progress)
        {
            DownLoadState = progress.State.ToString()+"  "+progress.Name;
            ProgressDownLoadValue = progress.ProgressRate;
            DownLoadStep = progress.CurrentSize + "/" + progress.TotalSize + " (" + progress.CurrentStep + "/" + progress.TotalStep + ")";
        }
        /// <summary>
        /// 下载完成
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="downloadPath"></param>
        /// <param name="fileId"></param>
        /// <param name="msg"></param>
        private void Updates_DownloadFinish(bool isSuccess, string downloadPath, UpdateState state, string msg = null, string name = null)
        {
            DownLoadState = state.ToString()+"  "+name;
            if (state == UpdateState.下载失败) {

               
                var dialogResult = MessageBox.Show("下载失败了,是否跳过本次下载,启动程序?\n错误信息:"+ msg, "下载失败", MessageBoxButton.OKCancel, MessageBoxImage.Error, MessageBoxResult.Yes, MessageBoxOptions.None);
                if (dialogResult == MessageBoxResult.Cancel)
                {
                    Process.GetCurrentProcess().Kill();
                }
                else
                {
                    //todo
                    //跳过本次更新的方式启动
                    try
                    {
                        if (File.Exists(ClientParameter.AppName))
                        {
                            Process.Start(ClientParameter.AppName, "jumpversion");
                        }                      
                    }
                    catch (Exception ex)
                    {
                       
                    }
                    finally
                    {
                        Process.GetCurrentProcess().Kill();
                    }
                }
            }
        }
        /// <summary>
        /// 解压进度
        /// </summary>
        /// <param name="progress"></param>
        private void Updates_UnZipProgressChanged(ZipModel progress)
        {
            UnZipState = progress.State.ToString()+progress.Name;
            ProgressUnZipValue = progress.ProgressRate;
            UnZipStep = progress.CurrentSize + "/" + progress.TotalSize + " (" + progress.CurrentStep + "/" + progress.TotalStep + ")";
        }
        /// <summary>
        /// 解压完成
        /// </summary>
        /// <param name="isSuccess"></param>
        /// <param name="msg"></param>
        private void Updates_UnZipFinish(bool isSuccess, UpdateState state, string msg = null)
        {
            UnZipState = state.ToString();
            if (state == UpdateState.解压失败)
            {
                var dialogResult = MessageBox.Show("解压失败了,是否回到上一版本,启动程序?\n错误信息:" + msg, "解压失败", MessageBoxButton.OKCancel, MessageBoxImage.Error, MessageBoxResult.Yes);
                if (dialogResult == MessageBoxResult.Cancel)
                {
                    Process.GetCurrentProcess().Kill();
                }
                else
                {
                    //todo
                    //跳过本次更新的方式启动
                    if (updates != null) {
                        updates.UnBackUp();
                    }
                }
            }
        }
    

        /// <summary>
        /// 全部下载完成
        /// </summary>
        private void Updates_AllFinish()
        {
            ProgressDownLoadValue = 100;
            ProgressUnZipValue = 100;
            MainTitle = "更新完成,等待系统自动启动...";
            

        }

        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string name) {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
    }
}
